<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/4/11
 * Time: 下午7:50
 */

namespace app\admin\controller;
use app\admin\model;

class Config extends Admin
{
    protected $templatePrefix = 'admin/config/';

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new model\Config();
    }

    /**
     * 配置首页
     * @return mixed
     */
    public function index()
    {
        $model = $this->model->where('status', '>=', 0)->order('`id` ASC')->field(true);

        $list = $this->lists($model);

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $this->assign('list', $list);

        return $this->fetch('index', ['list'=>$list]);
    }

    /**
     * 站点配置
     * @return mixed
     */
    public function webset()
    {
        $groupId = input('groupid', 1);

        $groupList = config('config_group_list');

        $list = $this->model->where('status', '99')->where('group', $groupId)->order('sort ASC, id ASC')->select();

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->fetch('webset', ['list'=>$list, 'groupList'=>$groupList]);
    }

    /**
     * 添加配置项
     * @return mixed
     */
    public function add()
    {
        $info = $this->model;
        $info->type = 0;
        $info->group = 1;
        $info->is_allow_change = 1; //  是否允许更改

        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 更新配置项
     * @return mixed
     */
    public function edit()
    {
        $id = input('param.id');

        if (empty($id)) {
            $this->error('缺少必要参数', cookie('__forward__'));
        }
        $info = $this->model->get($id);

        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 保存配置
     */
    public function save()
    {
        if (!$this->request->isPost()) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $id = input('post.id');

        if (empty($id)) {
            $info = $this->model->where('name', '=', input('name'))->find();
            if ($info) {
                $this->error('该标识已经存在');
            }
            $re = $this->model->data($_POST)->allowField(true)->save();
        } else {
            $re = $this->model->allowField(true)->save($_POST, ['id' => $id]);
        }

        if ($re === false) {
            $this->error('操作失败');
        }

        $this->success('操作成功', cookie('__forward__'));
    }

    /**
     * 保存站点配置数据
     */
    public function saveData()
    {
        if (!$this->request->isPost()) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $config = $_POST['config'];

        if($config && is_array($config)){
            foreach ($config as $name => $value) {
                $this->model->where(['name'=>$name])->setField('value', $value);
            }
        }

        $this->success('站点配置保存成功', cookie('__forward__'));
    }
}